import pandas as pd
from openpyxl import load_workbook
import os
import openpyxl.utils
from PIL import Image
import io

def return_headers(account_id=None):
    return {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/json",
        "origin": "https://ad.xiaohongshu.com",
        "priority": "u=1, i",
        "referer": f"https://ad.xiaohongshu.com/asset/schemeAssetManage?vSellerId={account_id}",
        "sec-ch-ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
        "v-seller-id": f"{account_id}",
        "x-b3-traceid": "12d70d203e516e18"
}

mock_click_js = """
function triggerFullClick(element) {
  // 1. 触发鼠标按下
  element.dispatchEvent(new MouseEvent('mousedown', {
    bubbles: true,
    cancelable: true,
    view: window
  }));

  // 2. 触发获取焦点
  element.focus();
  element.dispatchEvent(new Event('focus', {bubbles: true}));

  // 3. 触发鼠标释放
  element.dispatchEvent(new MouseEvent('mouseup', {
    bubbles: true,
    view: window
  }));

  // 4. 触发最终点击
  element.dispatchEvent(new MouseEvent('click', {
    bubbles: true,
    view: window
  }));
}

// 执行函数
triggerFullClick(this);
"""

default_file_name = "0421薇诺娜信息流计划搭建2.xlsx"

# 设置显示所有列（默认只显示部分列）
pd.set_option('display.max_columns', None)

# 设置显示所有行（默认只显示部分行）
pd.set_option('display.max_rows', None)

# 设置列宽（防止内容被截断）
pd.set_option('display.max_colwidth', 100)  # 设置每列最大显示宽度
def get_ad_config(row):
    if row['路径名称'] == "唤端1":
        return {
            '营销诉求': '应用推广',
            '营销目标': '应用唤起',
            '投放模式': '手动投放',
            '广告类型': '信息流推广',
            '推广目标': 'APP打开（唤起）',
            '出价方式': '自动出价',
            '成本控制方式': '点击成本控制 ',
            '广告组': '不加入'
        }
    else:
        return None  # 或者返回一个默认配置


def get_set_note_ids(df=None, file_path=None):
    note_ids = []
    for item in df['笔记ID'].tolist():
        ids = [x.strip() for x in item.split('\n') if x.strip()]
        note_ids.extend(ids)

    search_comp = get_search_comp(file_path)  # 转化组件中的笔记ID
    comp_note_ids = search_comp['笔记ID'].tolist()

    main_set = set(note_ids)
    comp_set = set(comp_note_ids)

    missing_ids = main_set - comp_set
    return missing_ids  # 主表中有但是附表中不存在的笔记ID



def get_complete_sheet1(file_path=None):
    df = pd.read_excel(file_path, sheet_name="计划列表")  # sheet_name 可省略
    config_df = df.apply(get_ad_config, axis=1, result_type='expand')
    df = pd.concat([df, config_df], axis=1)
    return df

def get_complete_sheet_platform(file_path=None):
    try:
        df = pd.read_excel(file_path, sheet_name="平台精选")
        cols_to_fill = ['人群定向包']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        return df
    except ValueError as e:
        if "Worksheet named '平台精选' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[平台精选]sheet")
            return pd.DataFrame()  # 返回带列名的空DF
        else:
            raise  # 重新抛出其他异常
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()

def get_complete_sheet_indus_people(file_path=None):
    """
    读取行业人群sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="行业人群")
        # 处理合并单元格
        cols_to_fill = ['人群定向包', '小类', '一级选项']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        print("成功加载数据:")
        print(df['人群定向包'].tolist())
        print(df.head())
        return df
    except ValueError as e:
        if "Worksheet named '行业人群' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[行业人群]sheet")
            return pd.DataFrame()  # 返回带列名的空DF
        else:
            raise  # 重新抛出其他异常
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()
def get_complete_sheet_indus_inters(file_path=None):
    """
    读取行业兴趣sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="行业兴趣")
        # 处理合并单元格
        cols_to_fill = ['人群定向包', '小类', '一级选项']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        print(df)
        return df
    except ValueError as e:
        if "Worksheet named '行业兴趣' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[行业兴趣]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()
def get_complete_sheet_keyword(file_path=None):
    """
    读取关键词sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="关键词").dropna(how="all")
        cols_to_fill = ['人群定向包']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        print(df)
        return df
    except ValueError as e:
        if "Worksheet named '关键词' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[关键词]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()
def get_complete_sheet_crowd_pack(file_path=None):
    """
    读取关键词sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="人群包")
        return df
    except ValueError as e:
        if "Worksheet named '人群包' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[人群包]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()

def get_search_comp(file_path=None):
    """
    读取搜索组件sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="唤端组件")
        return df
    except ValueError as e:
        if "Worksheet named '搜索组件' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[唤端组件]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()

def get_direct_link_sheet(file_path=None):
    """
    读取直达链接预先录入sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="直达链接预先录入")
        return df
    except ValueError as e:
        if "Worksheet named '直达链接预先录入' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[直达链接预先录入]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()


def read_excel_with_images(file_path, sheet_name='唤端组件', output_folder=None, plan_name=None):
    """
    同时读取 Excel 表格中的文本内容和图片，并建立行列 -> 图片路径的映射关系，
    并将图片大小统一调整为 78x78 像素。
    """
    try:
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)

        # 1️⃣ 使用 pandas 读取文本数据
        df = pd.read_excel(file_path, sheet_name=sheet_name)

        # 2️⃣ 使用 openpyxl 加载工作簿并提取图片
        wb = load_workbook(file_path)
        ws = wb[sheet_name]

        image_map = {}  # 存储 { (行号, 列号): 图片路径 }

        for idx, img in enumerate(ws._images):
            from_marker = img.anchor._from

            # 获取行列信息
            col_num_openpyxl = from_marker.col  # 列索引（0-based）
            row_num_openpyxl = from_marker.row  # 行号（1-based）

            # 转换为 pandas DataFrame 的行列索引
            row_num_df = row_num_openpyxl - 1
            col_num_df = col_num_openpyxl

            # 获取扩展名
            ext = img.ref.split('.')[-1] if '.' in img.ref else 'png'

            # 单元格位置用于命名文件
            cell_pos = f"{openpyxl.utils.get_column_letter(col_num_openpyxl + 1)}{row_num_openpyxl}"

            # 图片保存路径
            img_path = os.path.join(output_folder, f"cell_{cell_pos}_image_{idx + 1}.{ext}")

            # 从 openpyxl 提取图片二进制数据
            img_data = io.BytesIO(img._data())

            # 使用 Pillow 打开图片
            pil_img = Image.open(img_data)

            # 调整图片大小为 78x78（可选：保持比例、裁剪等）
            resized_img = pil_img.resize((78, 78), Image.Resampling.LANCZOS)

            # 保存为临时文件（自动处理格式）
            resized_img.save(img_path)

            # 建立映射关系
            image_map[(row_num_df, col_num_df)] = img_path

        return df, image_map
    except ValueError as e:
        if "Worksheet named '唤端组件' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[唤端组件]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()